package com.starblink.store.recommend.ui

import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.google.android.material.appbar.AppBarLayout.OnOffsetChangedListener
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.bean.LoadAction
import com.starblink.basic.apollo.ext.ApolloValSetExt
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.dp2px
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.user.LoginCheckInterceptor
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.android.basic.util.bus.bean.FollowStoreEvent
import com.starblink.android.basic.util.bus.bean.RemoveStoresEvent
import com.starblink.basic.route.RoutePage
import com.starblink.basic.style.title.OnTitleBarListener
import com.starblink.basic.style.title.TitleBar
import com.starblink.basic.style.view.recyclerview.SimpleGapItemDecor
import com.starblink.rocketreserver.fragment.MerchantWebVOF
import com.starblink.store.R
import com.starblink.store.databinding.ActivityRecommendStoreBinding
import com.starblink.store.recommend.adapter.MyFavoriteStoresHolder
import com.starblink.store.recommend.part.RecommendStorePart
import kotlin.math.absoluteValue


/**
 * 推荐店铺页
 */
@Route(path = RoutePage.Store.PAGE_HOME_RECOMMEND)
class RecommendStoreActivity :
    BaseTVMActivity<ActivityRecommendStoreBinding, RecommendStoreVM>() {

    @Autowired(name = RoutePage.Store.STORE_NUM)
    @JvmField
    var storeNum: Int = 0

    override fun initViewBinding(): ActivityRecommendStoreBinding =
        ActivityRecommendStoreBinding.inflate(layoutInflater)

    private val myAdapter: MutableAdapter by lazyOnNone {
        MutableAdapter(viewModel.myList.value!!).apply {
            addVhDelegate {
                MyFavoriteStoresHolder(
                    it, pageTrackTag = this.hashCode().toString()
                )
            }
        }
    }

//    private val recFragment by lazyOnNone {
//        StoreRecommendFragment(viewModel)
//    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setStatusBarWhiteText()

        RecommendStorePart.handleVM(
            this,
            this,
            viewBinding.rv,
            viewBinding.refresher,
            viewModel,
            isNestedScrollingEnabled = true,
            SpmPageDef.StoreMainRecommendListPage,
            pageTrackTag = this.hashCode().toString()
        )
//        FragmentUtils.add(
//            supportFragmentManager,
//            recFragment,
//            R.id.fragment_recommend
//        )
        viewBinding.recyclerMyFavourite.layoutManager =
            GridLayoutManager(this, 5)
        viewBinding.recyclerMyFavourite.addItemDecoration(
            SimpleGapItemDecor(horGap = 5, withEdge = true)
        )
        viewBinding.recyclerMyFavourite.adapter = myAdapter

        viewModel.loadMyRecommendStores(showLoading = true)
        viewModel.loadRecommendStores(showLoading = false)

        //同步订阅数据
        FlowBus.with<FollowStoreEvent>(FlowConst.FOLLOW_STORE_EVENT).register(this) {
            if (it.id != null) {
                if (it.followed) {
                    if (it.merchant != null) {
                        viewModel.addStore(it.merchant!!)
                    } else {
                        viewModel.loadMyRecommendStores(showLoading = false)
                    }
                } else {
                    for ((index, post) in viewModel.myList.value!!.withIndex()) {
                        if (post != null && post is MerchantWebVOF && it.id == post.id) {
                            viewModel.myList.value!!.removeAt(index)
                            viewModel.myList.value = viewModel.myList.value
                            break
                        }
                    }
                    if (viewModel.myList.value?.isEmpty() == true) {
                        viewBinding.tvMyF.visibleOrGone(false) {}
                    }
                }
                refreshRecommendListSub(it.id!!, it.followed)
            }
        }

        //同步取消店铺
        FlowBus.with<RemoveStoresEvent>(FlowConst.REMOVE_STORE_EVENT).register(this) {
            if (it.ids != null) {
                var removed = false
                for (id in it.ids!!) {
                    val first = viewModel.myList.value!!.indexOfFirst { it.id == id }
                    viewModel.myList.value!!.removeAt(first)

                    val ind = viewModel.queryMyList.indexOfFirst { it.id == id }
                    viewModel.queryMyList.removeAt(ind)
                    removed = true

                    refreshRecommendListSub(id, false)
                }
                if (removed) {
                    viewModel.myList.value = viewModel.myList.value
                    if (viewModel.myList.value?.isEmpty() == true) {
                        viewBinding.tvMyF.visibleOrGone(false) {}
                    }
                }
            }
        }

        FlowBus.with<Boolean>(FlowConst.LOGIN_STATUS_CHANGE).register(this) {
            viewModel.loadMyRecommendStores(showLoading = false)
            viewBinding.dialogLogin.content.visibleOrGone(!UserDataCenter.isLogin()) {}
        }
        setListener()
        startObserve()

    }

    private fun refreshRecommendListSub(id: String, sub: Boolean) {
        //刷新推荐列表订阅状态
        val index = viewModel.recommendList.value!!.indexOfFirst { it.id == id }
        if (index >= 0) {
            val merchant = viewModel.recommendList.value!![index]
            if (merchant.subOrNot != sub) {
                ApolloValSetExt.setApolloVal<MerchantWebVOF>(merchant, "subOrNot", sub)
                viewModel.recommendList.value!![index] = merchant
            }
            viewModel.recommendList.value = viewModel.recommendList.value
        }
    }

    private fun setListener() {
        viewBinding.title.setOnTitleBarListener(object : OnTitleBarListener {
            override fun onLeftClick(titleBar: TitleBar?) {
                finish()
            }

            override fun onRightClick(titleBar: TitleBar?) {
                navigationTo(RoutePage.Store.PAGE_MANAGE) {
                }
            }
        })
        viewBinding.searchItem.setOnClickListener {
            navigationTo(RoutePage.Search.PAGE_SEARCH) {
                withInt(RoutePage.Search.ARG_SCENE, RoutePage.Search.SCENE.STORES.value)
            }
        }

        viewBinding.dialogLogin.content.visibleOrGone(!UserDataCenter.isLogin()) {}
        viewBinding.dialogLogin.tvLogin.setOnClickListener {
            LoginCheckInterceptor.check2Login(this) {
            }
        }
        viewBinding.dialogLogin.ivCloseLogin.setOnClickListener {
            viewBinding.dialogLogin.content.visibleOrGone(false) {}
        }

        viewBinding.tvMyMore.run {
            trackData(
                page = SpmPageDef.SubscribeRecommendStoresPage,
                element = SpmElementDef.GdsSeemoreWidget,
                onlyHit = true,
            )
            click {
                viewModel.showAllMyStore()
            }
        }
        viewBinding.tvStoreNum.text =
            "${resources.getString(com.starblink.basic.style.R.string.explore)} $storeNum ${
                resources.getString(com.starblink.basic.style.R.string.store_num)
            }"

        viewBinding.appBar.addOnOffsetChangedListener(OnOffsetChangedListener { _, verticalOffset ->
            if (verticalOffset.absoluteValue > dp2px(250f)) {
                if (viewModel.barIsWhite.value != false) {
                    viewModel.barIsWhite.postValue(false)
                }
            } else {
                if (viewModel.barIsWhite.value != true) {
                    viewModel.barIsWhite.postValue(true)
                }
            }
//            Log.d("RecommendStoreActivity","RecommendStoreActivity--------$verticalOffset-----${dp2px(250f)}")
        })
    }

    private fun startObserve() {
        viewModel.showViewMore.observe(this) {
            viewBinding.tvMyMore.visibleOrGone(it) {

            }
        }

        viewModel.barIsWhite.observe(this) {
            if (viewModel.barIsWhite.value == true) {
                setStatusBarWhiteText()
                viewBinding.title.setTitleColor(ColorStateList.valueOf(Color.WHITE))
                viewBinding.title.setBackgroundResource(com.starblink.basic.style.R.color.transparent)
                viewBinding.title.setLeftIcon(com.starblink.basic.style.R.mipmap.icon_white_back)
                viewBinding.title.setRightIcon(R.mipmap.icon_store_setting)
            } else {
                setStatusBarBlackText()
                viewBinding.title.setBackgroundResource(com.starblink.basic.style.R.color.sk_gray50)
                viewBinding.title.setTitleColor(ColorStateList.valueOf(Color.BLACK))
                viewBinding.title.setLeftIcon(com.starblink.basic.style.R.mipmap.icon_black_back)
                viewBinding.title.setRightIcon(R.mipmap.icon_store_setting_2)
            }
        }

        viewModel.myList.observe(this) {
            viewBinding.layoutMyStore.visibleOrGone(viewModel.myList.value?.isNotEmpty() == true) {
                myAdapter.notifyDataSetChanged()
                Log.d("RecommendStoreActivity", "-----${it.size}")
                viewBinding.tvMyF.visibleOrGone(true) {}
            }
        }

        viewModel.mLoadActionLiveData.observe(this) {
            if (viewModel.mLoadActionLiveData.value == LoadAction(LoadAction.STATE_NO_DATA)) {
                viewBinding.empty.visibleOrGone(true) {}
                viewBinding.refresher.visibleOrGone(false) {}
            }
        }

        viewModel.recommendList.observe(this) {
            if (viewModel.recommendList.value!!.isNotEmpty()) {
                viewBinding.empty.visibleOrGone(false) {}
                viewBinding.ivLoading.visibleOrGone(false) {}
                viewBinding.refresher.visibleOrGone(true) {}
            } else {
                if (viewModel.loadedRecommend) {
                    viewBinding.empty.visibleOrGone(true) {}
                    viewBinding.refresher.visibleOrGone(false) {}
                    viewBinding.ivLoading.visibleOrGone(false) {}
                }
            }
        }
    }


    override fun onResume() {
        super.onResume()
        pageExposure(SpmPageDef.SubscribeRecommendStoresPage)
    }

    override fun onPause() {
        super.onPause()
        pageDisappear(SpmPageDef.SubscribeRecommendStoresPage)
    }

    override fun onDestroy() {
        super.onDestroy()
    }
}